<template>
  <div class="common-layout linear-gradient">
    <el-container>
      <el-header class="header-container">
        <el-card title="查询条件" class="header-card">
          <template #header>
            <div class="header-card-header">
              <span>查询条件</span>
            </div>
          </template>
          <el-form :model="headerSearchForm" label-width="auto" class="header-search-form" :inline="true">
            <el-form-item label="时间">
              <el-date-picker
                v-model="headerSearchForm.dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期时间"
                end-placeholder="结束日期时间"
                class="custom-date-picker"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :clearable="true"
              />
            </el-form-item>
            <el-form-item class="header-buttons">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
              <el-button type="primary" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-header>
      <el-main>
        <div class="table-container-main">
          <el-table
            :data="tableData"
            :stripe="true"
            :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            ref="tableRef"
          >
            <el-table-column prop="serialNumber" label="序号" fixed="left">
              <template #default="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="entId" label="入口卷号" min-width="160px" fixed="left" />
            <el-table-column prop="startTime" label="开始生产时间" min-width="200px" />
            <el-table-column prop="endTime" label="结束生产时间" min-width="200px" />
            <el-table-column prop="steelGrade" label="钢种" min-width="120px" />
            <el-table-column prop="thickness" label="厚度" />
            <el-table-column prop="width" label="宽度" />
            <el-table-column prop="thicknessLowerLimit" label="厚度下限" />
            <el-table-column prop="thicknessUpperLimit" label="厚度上限" />
            <el-table-column prop="widthLowerLimit" label="宽度下限" />
            <el-table-column prop="widthUpperLimit" label="宽度上限" />
            <el-table-column prop="zincWeight" label="锌层重量" />
            <el-table-column prop="zincTarget" label="锌层目标" />
            <el-table-column prop="zincLowerLimit" label="锌层下限" />
            <el-table-column prop="zincUpperLimit" label="锌层上限" />
            <el-table-column prop="coarseGrainedTarget" label="粗糙度目标" />
            <el-table-column prop="coarseGrainedLowerLimit" label="粗糙度下限" />
            <el-table-column prop="coarseGrainedUpperLimit" label="粗糙度上限" />
            <el-table-column prop="washQuantity" label="涂油量" />
            <el-table-column prop="rawMaterialLength" label="原料长度" />
            <el-table-column prop="rawMaterialWeight" label="原料重量" />
          </el-table>
        </div>
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, onUnmounted } from 'vue';
  import { ElMessage, ElTable } from 'element-plus';
  import * as XLSX from 'xlsx';

  interface SearchForm {
    dateRange: Date[];
  }

  // 表单数据
  const headerSearchForm = reactive<SearchForm>({
    dateRange: [],
  });

  // 表格数据
  const tableData = ref([
    {
      serialNumber: '1',
      entId: '卷号1',
      startTime: '2023-01-01 12:00:00',
      endTime: '2023-01-01 15:00:00',
      steelGrade: '钢种1',
      thickness: '2.0',
      width: '1000',
      thicknessLowerLimit: '1.8',
      thicknessUpperLimit: '2.2',
      widthLowerLimit: '990',
      widthUpperLimit: '1010',
      zincWeight: '150',
      zincTarget: '150',
      zincLowerLimit: '140',
      zincUpperLimit: '160',
      coarseGrainedTarget: '0.02',
      coarseGrainedLowerLimit: '0.01',
      coarseGrainedUpperLimit: '0.03',
      washQuantity: '10',
      rawMaterialLength: '3000',
      rawMaterialWeight: '15',
    },
    {
      serialNumber: '2',
      entId: '卷号2',
      startTime: '2023-01-02 13:00:00',
      endTime: '2023-01-02 16:00:00',
      steelGrade: '钢种2',
      thickness: '2.1',
      width: '1010',
      thicknessLowerLimit: '1.8',
      thicknessUpperLimit: '2.2',
      widthLowerLimit: '990',
      widthUpperLimit: '1010',
      zincWeight: '160',
      zincTarget: '150',
      zincLowerLimit: '140',
      zincUpperLimit: '160',
      coarseGrainedTarget: '0.02',
      coarseGrainedLowerLimit: '0.01',
      coarseGrainedUpperLimit: '0.03',
      washQuantity: '12',
      rawMaterialLength: '3010',
      rawMaterialWeight: '15.5',
    },
  ]);
  const tableRef = ref<InstanceType<typeof ElTable>>();

  // 分页数据
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 1,
  });

  // 获取表格数据
  const fetchTableData = async () => {
    let start, end;
    if (headerSearchForm.dateRange && headerSearchForm.dateRange.length === 2) {
      [start, end] = headerSearchForm.dateRange;
    }
    try {
      const param = {
        page: {
          pageIndex: pagination.currentPage,
          pageSize: pagination.pageSize,
        },
        dto: {
          startDate: start,
          endDate: end,
        },
      };
      // const res = await listApi.getTableData(param);
      // tableData.value = res.data.data.records;
      // pagination.total = res.data.data.total;
    } catch (error) {
      ElMessage.error('获取数据失败');
    }
  };

  // 查询方法
  const handleSearch = () => {
    pagination.currentPage = 1;
    fetchTableData();
  };

  // 重置方法
  const handleReset = () => {
    headerSearchForm.dateRange = [];
    handleSearch();
  };

  // 导出方法
  const handleExport = () => {
    if (!tableData.value.length) {
      ElMessage.error('导出Excel失败: 当前暂无数据');
      return;
    }

    try {
      // 动态获取表格列配置
      const columns = tableRef.value?.columns;

      if (!columns || !(Array.isArray(columns) && columns.length)) {
        ElMessage.error('导出Excel失败: 表格列配置错误');
        return;
      }

      // 添加新的属性到 headerMap
      const headerMap: Record<string, string> = {};

      // 构建字段到标签的映射
      columns.forEach((column: any) => {
        if (column.property && column.property !== 'serialNumber') {
          headerMap[column.property] = column.label;
        }
      });

      delete headerMap['serialNumber'];

      // 构建字段名数组
      const columnProperties = Object.keys(headerMap);

      // 转换数据为 worksheet
      const ws = XLSX.utils.json_to_sheet(tableData.value, { header: columnProperties });

      // 添加中文表头
      const headerRow = Object.values(headerMap);
      XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: 'A1' });

      // 创建 workbook 并添加 worksheet
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 格式化日期和时间
      const formattedDateTime = new Date()
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        })
        .replace(/\//g, '-')
        .replace(/\s/g, '_')
        .replace(/:/g, '-');

      // 生成 Excel 文件并下载
      XLSX.writeFile(wb, '工艺参数数据' + formattedDateTime + '.xlsx');
      ElMessage.success('导出成功');
    } catch (error: any) {
      ElMessage.error('导出Excel失败: ' + error.message);
      console.error('导出Excel时出错:', error);
    }
  };

  // 分页大小变化
  const handleSizeChange = (val: number) => {
    pagination.pageSize = val;
    fetchTableData();
  };

  // 页码变化
  const handleCurrentChange = (val: number) => {
    pagination.currentPage = val;
    fetchTableData();
  };

  // 生命周期钩子
  onMounted(() => {
    fetchTableData();
  });

  onUnmounted(() => {});
</script>
<style lang="less" scoped>
  @border-radius: 8px;
  @primary-color: #2c69e8;
  @box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  .common-layout {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #fff;
    overflow: hidden;

    &.linear-gradient {
      background-image: linear-gradient(to top, white, @primary-color) !important;
    }
  }

  .table-container-main {
    border-radius: @border-radius;
    height: 70vh;
    background-color: #fff;
    box-shadow: @box-shadow;
    display: flex;

    .el-table {
      margin: 0.5% auto;
      width: calc(100% - 40px);
      height: calc(100% - 40px);
    }
  }

  .pagination {
    margin-top: 2vh;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }

  .header-container {
    margin-top: 5px;
    height: 11vh;
    .el-card {
      :deep(.el-card__header) {
        height: 3vh;
        display: flex;
        align-items: center;
      }
      :deep(.el-card__body) {
        height: 7vh;
        display: flex;
        align-items: center;

        .el-form {
          margin-top: 15px;
        }
      }
    }
  }
</style>
